/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    struct ListNode* A = headA, *B = headB;
    while(A!=B)
    {
        A = A != NULL ? A->next : headB;
        B = B != NULL ? B->next : headA;
    }
    return A;
}

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    struct ListNode* curA = headA;
    struct ListNode* curB = headB;

    int lenA = 1, lenB = 1, gap = 0;

    while(curA->next)
    {
        lenA++;
        curA = curA->next;
    }

    while(curB->next)
    {
        lenB++;
        curB = curB->next;
    }

    if(curA != curB)
        return NULL;

    struct ListNode* shortList = headA;
    struct ListNode* longList = headB;

    if(lenA > lenB)
    {
        longList = headA;
        shortList = headB; 
    }
    else
    {
        longList = headB;
        shortList = headA; 
    }

    gap = abs(lenA - lenB);

    while(gap--)
    {
        longList = longList->next;
    }

    while(longList != shortList)
    {
        longList = longList->next;
        shortList = shortList->next;
    }

    return shortList;
}